package com.sgolub.commanndsonline.dao.entity;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.sgolub.commanndsonline.domain.entity.AdvertisingRegistry;

@Repository
public class AdvertisingRegistryDAOImpl implements AdvertisingRegistryDAO {

    @Autowired
    private SessionFactory sessionFactory;
    
	public AdvertisingRegistry get(Integer id) {
		AdvertisingRegistry advertisingRegistry = (AdvertisingRegistry)sessionFactory.
								getCurrentSession().load(AdvertisingRegistry.class, id);
		return advertisingRegistry;
	}

	public void add(AdvertisingRegistry advertisingRegistry) {
		sessionFactory.getCurrentSession().save(advertisingRegistry);

	}

	public void update(AdvertisingRegistry advertisingRegistry) {
		// TODO Auto-generated method stub

	}

	public void remove(Integer id) {
		// TODO Auto-generated method stub

	}

	@SuppressWarnings("unchecked")
	public List<AdvertisingRegistry> list() {
		return sessionFactory.getCurrentSession().createQuery("from AdvertisingRegistry").list();
	}

	@SuppressWarnings("unchecked")
	public List<AdvertisingRegistry> filter() {
		return sessionFactory.getCurrentSession().createQuery("from AdvertisingRegistry").list();
	}

	@SuppressWarnings("unchecked")
	public List<AdvertisingRegistry> advansedListWithPagination(int rp, String sortorder, 
			int page, String query, String sortname, String qtype ){
		List<AdvertisingRegistry> result = new ArrayList<AdvertisingRegistry>();
		String sqlFrom = "from AdvertisingRegistry";
		String sqlWhere = "";
		String sqlOrder = "";
		String sql = "";
		
		if (query.length()>0 && qtype.length()>0) {
			sqlWhere = " where " + qtype + " like '%" + query + "%' ";
		}
		
		if (sortname.length()>0 && sortorder.length()>0) {
			sqlOrder = " order by " + sortname + " " + sortorder;
		}
		
		sql = sqlFrom + sqlWhere + sqlOrder;
		
		
		System.out.println("Query = " + sql);
		
		Query queryH = sessionFactory.getCurrentSession().createQuery(sql);
		queryH.setFirstResult(rp * (page-1));
		queryH.setMaxResults(rp);
		
		return queryH.list();
	}
	
}
